<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-06-03 09:21:17
 * @LastEditors: william
 * @LastEditTime: 2025-10-27 15:03:22
-->
<template>
  <up-picker
    ref="uPickerRef"
    v-model="modelValue"
    v-model:show="show"
    :defaultIndex="defaultIndex"
    :columns="columns"
    :keyName="keyName"
    :valueName="valueName"
    :closeOnClickOverlay="true"
    :cancelText="$t('public.cancel')"
    :confirmText="$t('public.sure')"
    cancelColor="#999"
    :confirmColor="g_style.mainRgbTheme"
    :="$attrs"
    @close="emit('close')"
    @cancel="emit('cancel')"
    @confirm="e => emit('confirm', e)"
  >
    <template #toolbar-right>
      <slot name="toolbar-right"></slot>
    </template>
    <template #toolbar-bottom>
      <slot name="toolbar-bottom"></slot>
    </template>
    <template #trigger>
      <slot name="trigger"></slot>
    </template>
  </up-picker>
</template>

<script setup>
defineOptions({
  name: 'ActionSheet',
  inheritAttrs: false
})

const props = defineProps({
  columns: {
    type: Array,
    default: () => []
  },
  keyName: {
    type: String,
    default: 'label'
  },
  valueName: {
    type: String,
    default: 'value'
  }
})

const modelValue = defineModel({
  type: Array,
  default: () => []
})
const show = defineModel('show', {
  type: Boolean,
  default: false
})
const defaultIndex = defineModel('defaultIndex', {
  type: Array,
  default: () => []
})
const emit = defineEmits(['close', 'cancel', 'confirm'])
const uPickerRef = ref(null)

watch(
  [() => props.show, () => props.columns, () => modelValue.value],
  (nv, ov) => {
    if (nv) getIndex()
  },
  {
    immediate: true,
    deep: true
  }
)

function getIndex() {
  defaultIndex.value = []
  props.columns.forEach((item, i) => {
    const index = item.findIndex(it => {
      if (Object.prototype.toString.call(it) === '[object Object]') {
        return it[props.valueName] === modelValue.value[i]
      } else {
        return it === modelValue.value[i]
      }
    })
    defaultIndex.value.push(index > -1 ? index : 0)
  })
  console.log('defaultIndex.value', defaultIndex.value)
}

defineExpose({
  ref: uPickerRef
})
</script>

<style lang="scss" scoped>
:deep(.u-popup__content) {
  border-radius: 10rpx 10rpx 0 0;
}
</style>
